/*
 ============================================================================
 Name        : usrSimpleApp.c
 Author      : VSP
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <error.h>
#include <malloc.h>
#include <netdb.h>
#include <netinet/in.h>
#include <assert.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include "control_cmd.h"
#include "pspHead.h"
#include "pspExternFunc.h"

#define XDMA_MLOCK
#define WORK_CPU_START (10)

extern void xdmaMemBufInit(void * usrBuf0, unsigned int usrBuf0Size,
		void * usrBuf1, unsigned int usrBuf1Size, void * usrBuf2,
		unsigned int usrBuf2Size, void * usrBuf3, unsigned int usrBuf3Size);


#define TEXT_SZ (1024*1024*1024)
#define XDMA_THREAD_NUM (32)

void *xdma_input_data = (void*) 0;
void *xdma_output_data = (void*) 0;
void *xdma_middle_data = (void*) 0;
void *xdma_coef_data = (void*) 0;

pthread_t xdma_t1[XDMA_THREAD_NUM];

extern sem_t xdmaSemInput;
extern int run_xdma_flag;

extern void sync_xdma_drvrecv();

int sync_xdma_main(int coreIndex)
{
	int ret = 0;
	int i = 0;
	cpu_set_t cpu_info;
	xdma_input_data = memalign(0x10000000, TEXT_SZ);
#ifdef XDMA_MLOCK
	mlock(xdma_input_data, TEXT_SZ);
#endif
	printf("input_data attached at %p.\n", xdma_input_data);

	xdmaMemBufInit(xdma_input_data, TEXT_SZ, 0,0,0,0,0,0);

	ret = sem_init(&xdmaSemInput, 0, 0);
	if (ret != 0)
	{
		printf("xdmaSemInput sem_init :failed.\n");
		return EXIT_FAILURE;
	}
	pthread_attr_t attr1[XDMA_THREAD_NUM];

	i = 1;
	pthread_attr_init(&attr1[i]);
	run_xdma_flag=1;
	if( 0!= pthread_create(&xdma_t1[i],&attr1[i],sync_xdma_drvrecv,(void*)0))
	{
		printf("fail to create drvrecv.\n");
		return(EXIT_FAILURE);
	}
	CPU_ZERO(&cpu_info);
	CPU_SET(coreIndex,&cpu_info);
	if( 0 != pthread_setaffinity_np(xdma_t1[i],sizeof(cpu_set_t),&cpu_info))
	{
		printf("drvrecv:set affinity failed\n");
	}

	return EXIT_SUCCESS;
}

void sync_exitXdma()
{
	run_xdma_flag = 0;
	pthread_join(xdma_t1[1],NULL);
	free(xdma_input_data);
	sem_destroy(&xdmaSemInput);
}
